package com.atguigu.sparkstreaming.exactlyonce

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Created by Smexy on 2022/8/22
 *
 *
 *  原理：   at least once + 幂等输出 =   exactly once
 *
 *
 *          ①取消offsets的自动提交
 *          ②获取偏移量
 *          ③幂等输出
 *          ④在输出后手动提交
 *
 *
 *
 */
object EndependentExactlyOnceDemo {

  def main(args: Array[String]): Unit = {


    val streamingContext = new StreamingContext("local[*]", "wordcount", Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "sz220409test",
      "auto.offset.reset" -> "latest",
      //①取消offsets的自动提交
      "enable.auto.commit" -> "false"
    )


    val topics = Array("topicD")

    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    ds.foreachRDD(rdd => {

      //②获取到当前批次的偏移量
      val ranges: Array[OffsetRange] = rdd.asInstanceOf[HasOffsetRanges].offsetRanges

      rdd.foreach(record => {

         //③幂等输出。 这里是伪代码，只是介绍此种编程的基本套路，具体输出什么，要看业务！


      })

      //④在输出后手动提交offsets
      ds.asInstanceOf[CanCommitOffsets].commitAsync(ranges)

    })


    streamingContext.start()

    streamingContext.awaitTermination()

  }

}
